<template>
  <div class="cart-container">
    <!-- 顶部区域 -->
    <h2>我的购物车</h2>

    <!-- 中间内容区域 -->
    <div class="cart-body">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated/>
      </div>

      <!-- 购物车为空时显示 -->
      <div v-else-if="isEmptyCart" class="empty-cart">
        <el-empty description="您的购物车还是空的">
          <template #image>
            <el-icon class="empty-icon">
              <ShoppingCart/>
            </el-icon>
          </template>
          <template #bottom>
            <el-button type="primary" @click="handleGoShopping">去购物</el-button>
          </template>
        </el-empty>
      </div>

      <!-- 购物车有商品时显示 -->
      <div v-else class="cart-list">
        <el-table
            :data="cartProducts"
            :header-cell-style="{ 'background-color': '#f5f7fa' }"
            border
            @row-click="handleRowClick"
        >
          <el-table-column align="center" label="选择" width="80">
            <template #default="scope">
              <el-checkbox
                  v-model="scope.row.selected"
                  :disabled="!isPurchasable(scope.row.productStatus)"
                  @click.stop
              >
                {{ scope.row.selected ? '已选' : '选择' }}
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="商品信息" width="350">
            <template #default="scope">
              <div class="product-info clickable">
                <el-image
                    :src="scope.row.productImage"
                    class="product-image"
                    fit="cover"
                ></el-image>
                <div class="product-details">
                  <span class="product-name">{{ scope.row.productName }}</span>
                  <span class="product-description">{{ scope.row.description }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.productPrice }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.productStatus)" size="small">
                {{ getStatusText(scope.row.productStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template #default="scope">
              <el-button
                  size="small"
                  type="danger"
                  @click.stop="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 底部结算区域 -->
    <div v-if="!isEmptyCart && !loading" class="cart-footer">
      <div class="cart-summary">
        <div class="select-info">
          <span v-if="selectedProducts.length > 0" class="selected-product">
            已选择 <strong>{{ selectedProducts.length }}</strong> 件商品
          </span>
          <span v-else class="no-selection">请选择商品进行结算</span>
        </div>
        <div v-if="selectedProducts.length > 0" class="total-price">
          合计：<span class="price">¥{{ totalPrice }}</span>
        </div>
      </div>
      <el-button
          :disabled="selectedProducts.length === 0"
          size="large"
          type="primary"
          @click="handleCheckout"
      >
        结算
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {ShoppingCart} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRouter} from 'vue-router'
import http from "@/request/Http.js"

const router = useRouter()

// 加载状态
const loading = ref(false)

// 购物车数据
const cartProducts = ref([])

// 计算属性 - 购物车是否为空
const isEmptyCart = computed(() => cartProducts.value.length === 0)

// 计算属性 - 选中的商品
const selectedProducts = computed(() => {
  return cartProducts.value.filter(item => item.selected && isPurchasable(item.productStatus))
})

// 计算属性 - 选中商品总价
const totalPrice = computed(() => {
  return selectedProducts.value.reduce((total, item) => total + item.productPrice, 0)
})

// 判断商品是否可购买
const isPurchasable = (status) => {
  return status === 1 // 只有上架状态的商品可购买
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',      // 已下架
    1: 'success',   // 可购买
    2: 'warning',   // 不可购买
    3: 'danger',    // 已售罄
    4: 'warning',   // 不可购买
    5: 'warning'    // 不可购买
  }
  return statusMap[status] || 'info'
}

// 获取状态对应的前端显示文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已下架',
    1: '可购买',
    2: '不可购买',
    3: '已售罄',
    4: '不可购买',
    5: '不可购买'
  }
  return statusMap[status] || '未知状态'
}

// 获取购物车数据
const fetchCartData = async () => {
  loading.value = true
  try {
    const response = await http.get(`/cart/list`)
    if (response.code === 200) {
      // 初始化选中状态，默认为false
      cartProducts.value = response.data.map(item => ({
        ...item,
        selected: false
      }))
    } else {
      ElMessage.error('获取购物车数据失败')
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    ElMessage.error('获取购物车数据失败')
  } finally {
    loading.value = false
  }
}

// 行点击事件 - 跳转到商品详情页
const handleRowClick = (row) => {
  if (row.productId) {
    router.push(`/userHome/showGood/${row.productId}`)
  } else {
    ElMessage.warning('商品ID不存在，无法跳转')
  }
}

// 删除商品
const handleDelete = async (product) => {
  try {
    await ElMessageBox.confirm(
        `确定要从购物车中移除"${product.productName}"吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    const response = await http.delete(`/cart/remove`, {
      data: {
        id: product.id,
        productId: product.productId
      }
    })

    if (response.code === 200) {
      // 从本地数据中移除
      const index = cartProducts.value.findIndex(item =>
          item.cartId === product.cartId && item.productId === product.productId
      )
      if (index !== -1) {
        cartProducts.value.splice(index, 1)
        ElMessage.success(`已从购物车中移除${product.productName}`)
      }
    } else {
      ElMessage.error('删除商品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }
}

// 去购物
const handleGoShopping = () => {
  router.push('/userHome') // 假设商品列表页路由为 '/userHome'
}

// 结算
const handleCheckout = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // try {
  //   // 为每个选中的商品创建订单 循环创建订单
  //   const orderPromises = selectedProducts.value.map(async (product) => {
  //     const orderData = {
  //       productId: product.productId,
  //       totalAmount: product.productPrice
  //
  //     }
  //
  //     // 调用创建订单的API
  //     return await http.post('/order/create', orderData)
  //   })
  //
  //   // 等待所有订单创建完成
  //   const results = await Promise.all(orderPromises)
  //
  //   // 检查所有订单是否创建成功
  //   const allSuccess = results.every(result => result.code === 200)
  //
  //   if (allSuccess) {
  //     ElMessage.success(`成功创建 ${selectedProducts.value.length} 个订单`)
  //
  //     // 这里可以添加跳转到订单页面的逻辑
  //      await router.push('userHome/Layout')
  //   } else {
  //     ElMessage.error('部分订单创建失败，请重试')
  //   }
  // } catch (error) {
  //   console.error('结算失败:', error)
  //   ElMessage.error('结算失败，请重试')
  // }

  //后台批量创建订单
  try {
    // 组装批量订单数据
    const batchOrderData = selectedProducts.value.map((product) => {
      return {
        productId: product.productId,
        totalAmount: product.productPrice
      };
    });
    // 调用批量创建订单的 API
    const result = await http.post('/order/createBatch', batchOrderData);
    // 可以根据 result 进行后续操作，比如判断是否批量创建成功等
    if (result.code === 200) {
      ElMessage.success(`成功创建 ${selectedProducts.value.length} 个订单`)
      await router.push({path: '/userHome/Layout', query: {page: 'order'}})
    } else {
      ElMessage.error('批量创建订单失败：', result.msg);
    }
  } catch (error) {
    console.error('批量创建订单失败：', error);
    ElMessage.error('批量创建订单失败：', error);
  }
}

// 初始化时获取购物车数据
onMounted(() => {
  fetchCartData()
})
</script>

<style scoped>
.cart-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-bottom: 80px; /* 为底部结算区域留出空间 */
}

.cart-body {
  flex: 1;
  padding: 20px;
  background-color: #f9fafb;
}

.loading-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.empty-cart {
  background-color: #fff;
  padding: 40px;
  border-radius: 4px;
  text-align: center;
}

.empty-icon {
  width: 60px;
  height: 60px;
  color: #ccc;
}

.cart-list {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.product-info {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.product-info.clickable {
  cursor: pointer;
}

.product-info.clickable:hover {
  background-color: #f5f7fa;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  border-radius: 4px;
}

.product-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.product-name {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
  margin-bottom: 8px;
  font-weight: 500;
}

.product-description {
  color: #666;
  font-size: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.cart-summary {
  display: flex;
  align-items: center;
  flex: 1;
}

.select-info {
  margin-right: 20px;
  color: #666;
  font-size: 14px;
  flex: 1;
}

.selected-product {
  color: #165dff;
}

.no-selection {
  color: #999;
  font-style: italic;
}

.total-price {
  font-size: 16px;
  font-weight: 500;
  min-width: 150px;
  text-align: right;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 20px;
  margin-left: 4px;
}

.cart-footer .el-button {
  min-width: 120px;
  height: 48px;
  font-size: 16px;
  font-weight: bold;
}

/* 复选框样式调整 */
:deep(.el-checkbox) {
  margin-right: 0;
}

:deep(.el-checkbox__label) {
  font-size: 12px;
  padding-left: 4px;
}
</style>